/**
 * Wechaty - Conversational RPA SDK for Chatbot Makers.
 *  - https://github.com/wechaty/wechaty
 */
 import {
  Contact,
  Message,
  ScanStatus,
  Wechaty,
  log,
} from 'wechaty'
import {createConnection} from "typeorm";
import { generate } from 'qrcode-terminal'
import { handleMessage, receivePayInfo } from './util/MessageHandle'

function onScan (qrcode: string, status: ScanStatus) {
  if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
    generate(qrcode, { small: true })  // show qrcode on console

    const qrcodeImageUrl = [
      'https://wechaty.js.org/qrcode/',
      encodeURIComponent(qrcode),
    ].join('')

    log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl)
  } else {
    log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status)
  }
}

function onLogin (user: Contact) {
  log.info('StarterBot', '%s login', user)
}

function onLogout (user: Contact) {
  log.info('StarterBot', '%s logout', user)
}

async function onMessage (message: Message) {
  log.info('StarterBot', message.toString())
  // getAllRoomInfo(bot)
  handleMessage(message,bot)
  receivePayInfo(message, bot)
}


const bot = new Wechaty({
  name: 'wechaty-public',
})

bot.on('scan',    onScan)
bot.on('login',   onLogin)
bot.on('logout',  onLogout)
bot.on('message', onMessage)
// 离开群
bot.on('room-leave', async (room, leaverList, remover) => {
  const nameList = leaverList.map(c => c.name()).join(',')
  console.log(`Room ${await room.topic()} lost member ${nameList}, the remover is: ${remover}`)
})
// 有人加入群
bot.on('room-join', async (room, inviteeList, inviter) => {
  const nameList = inviteeList.map(c => c.name()).join(',')
  console.log(`Room ${await room.topic()} got new member ${nameList}, invited by ${inviter}`)
})

// 群邀请
bot.on('room-invite',async roomInvitation => {
  console.log(`received room-invite event.`)
  await roomInvitation.accept()
})

// error Event will emit when there's an error occurred.
bot.on('error', (error) => {
  console.error(error)
})

createConnection().then(async connection => {
  console.log('创建数据库连接')
  bot.start()
  .then(() => log.info('StarterBot', 'Starter Bot Started.'))
  .catch(e => log.error('StarterBot', e))
}).catch(error =>{
  console.log(error)
})

